package com.httpDemo.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.httpDemo.doMain.User;
import com.httpDemo.mapper.UserMapper;
import com.httpDemo.service.UserService;

@Service
@Transactional // 声明事务，需先在启动类上添加@EnableTransactionManagement注解
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;

	@Override
	@CacheEvict(cacheNames = "user", key = "#id") // 删除缓存
	public int deleteById(Integer id) {
		return userMapper.deleteById(id);
	}

	@Override
	@CachePut(cacheNames = "user", key = "#result.id") // 新增缓存
	public User save(User user) {
		userMapper.save(user);
		return user;
	}

	@Override
	@CachePut(cacheNames = "user", key = "#user.id") // 修改缓存
	public User update(User user) {
		userMapper.update(user);
		return user;
	}

	@Override
	@Cacheable(cacheNames = "user", key = "#id") // 从缓存中查询，新增和修改的返回值必须与查询一致
	@Transactional(readOnly = true)
	public User findById(Integer id) {
		return userMapper.findById(id);
	}

	@Override
	@Cacheable(cacheNames = "user", key = "#pageNum+'-'+#pageSize") // key值可以多个变量拼接
	@Transactional(readOnly = true)
	public PageInfo<User> findAll(int pageNum, int pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		PageInfo<User> pageInfo = new PageInfo<>(userMapper.findAll());
		return pageInfo;
	}

}
